package com.jing.tanksnack.entity;

import com.jing.tanksnack.config.ServerConfig;
import org.springframework.beans.factory.annotation.Value;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 坦克游戏的服务器
 * @author mashibing
 *
 */
public class TankServer {

	List<Client> clients = new ArrayList<Client>();
	
	/**
	 * 启动服务器
	 *
	 */
	public void start() throws UnknownHostException {
		InetAddress addr = InetAddress.getLocalHost();
		String hostname = addr.getHostName();
		new Thread(new UDPThread()).start();

		ServerSocket ss = null;
		try {
			ss = new ServerSocket(ServerConfig.serverTcpPort);
		} catch (IOException e) {
			e.printStackTrace();
		}

		while (true) {
			Socket s = null;
			try {
				System.out.println("服务器启动：ip"+addr.getHostAddress()+" hostname:"+hostname);
				System.out.println("tcp端口号"+ServerConfig.serverTcpPort);
				System.out.println("udp端口号"+ServerConfig.serverUdpPort);
				s = ss.accept();
				DataInputStream dis = new DataInputStream(s.getInputStream());
				String IP = s.getInetAddress().getHostAddress();
				int udpPort = dis.readInt();
				Client c = new Client(IP, udpPort);
				clients.add(c);
				DataOutputStream dos = new DataOutputStream(s.getOutputStream());
				dos.writeInt(ServerConfig.id++);
				System.out.println("客户端连接成功" + s.getInetAddress() + ":" + s.getPort() + "----UDP Port:" + udpPort);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (s != null) {
					try {
						s.close();
						s = null;
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}


	private class Client {
		String IP;
		int udpPort;
		public Client(String IP, int udpPort) {
			this.IP = IP;
			this.udpPort = udpPort;
		}
	}

	private class UDPThread implements Runnable {

		byte[] buf = new byte[1024];

		public void run() {
			DatagramSocket ds = null;
			try {
				ds = new DatagramSocket(ServerConfig.serverUdpPort);
			} catch (SocketException e) {
				e.printStackTrace();
			}
			System.out.println("UDP服务器启动 :" + ServerConfig.serverUdpPort);
			while (ds != null) {
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				try {
					ds.receive(dp);
					System.out.printf("收到客户端"+dp.getSocketAddress()+" "+dp.getAddress()+":"+dp.getPort()+"发来的信息");
					for (int i = 0; i < clients.size(); i++) {
						Client c = clients.get(i);
						dp.setSocketAddress(new InetSocketAddress(c.IP, c.udpPort));
						ds.send(dp);
						System.out.printf("发送信息到"+dp.getSocketAddress()+" "+dp.getAddress()+":"+dp.getPort());
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}
